﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UCNKompetenceBors.Database;
using UCNKompetenceBors.Model;

namespace UCNKompetenceBors
{
    public partial class news : System.Web.UI.Page
    {
        private PagedDataSource _pagedDataSource = new PagedDataSource();

        private int _itemsPerPage = 6;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                #region Globalization
                string culture = String.Empty;

                if (HttpContext.Current.Session["MyCulture"] != null)
                    culture = HttpContext.Current.Session["MyCulture"].ToString();

                if (!String.IsNullOrEmpty(culture))
                    GeneralTools.SetCulture(culture);

                LocalizeControls();
                #endregion

                #region Bind Data
                BindLatestNews();

                if (Request.QueryString["i"] != null)
                {
                    _itemsPerPage = Convert.ToInt32(Request.QueryString["i"]);
                    ddlResultsPerPage.SelectedValue = Request.QueryString["i"].ToString();
                }

                BindNewsArchive(_itemsPerPage);
                #endregion

                #region Pagination
                CreatePagination();
                #endregion
            }
        }

        /// <summary>
        /// Binds the latest news article to the latest news box.
        /// </summary>
        private void BindLatestNews()
        {
            
            string culture = String.Empty;

            if (HttpContext.Current.Session["MyCulture"] != null)
                culture = HttpContext.Current.Session["MyCulture"].ToString();

            News news = null;

            if (culture.Equals("en-GB"))
                news = dbNews.GetLatestNewsArticle(culture);
            else
                news = dbNews.GetLatestNewsArticle();


            if (news != null)
            {
                lblLatestNewsTitle.Text = news.Title;
                lblLatestNewsDateAndAuthor.Text = news.CreatedDate.ToString("dd-MM-yyyy") + ", " + news.User.UserName;
                string newsText = GeneralTools.TruncateString(news.Text, 800, ".");
                lblLatestNewsText.Text = newsText.Replace("<br />", Environment.NewLine);
                hyLinkLatestNews.NavigateUrl = "~/newsDetails.aspx?nid=" + news.NewsId;
                hyLinkLatestNews.Visible = true;
                imgLatestNewsImage.ImageUrl = news.ImageURL; 
            }
            else
            {
                lblLatestNewsText.Text = "Der er ikke nogle nyheder på nuværende tidspunkt";
                hyLinkLatestNews.Visible = false;
            }
            
        }

        /// <summary>
        /// Binds the news archive to the dlNewsArchive datalist.
        /// </summary>
        private void BindNewsArchive(int itemsPerPage)
        {
            string culture = String.Empty;

            if (HttpContext.Current.Session["MyCulture"] != null)
                culture = HttpContext.Current.Session["MyCulture"].ToString();

            List<News> news = new List<News>();

            if (culture.Equals("en-GB"))
                news = dbNews.GetAllNewsWithOffset(culture);
            else
                news = dbNews.GetAllNewsWithOffset();

            _pagedDataSource.DataSource = news;
            _pagedDataSource.AllowPaging = true;
            _pagedDataSource.PageSize = itemsPerPage;

            if (Request.QueryString["p"] != null)
            {
                _pagedDataSource.CurrentPageIndex = Convert.ToInt32(Request.QueryString["p"]) - 1;
            }
            else
            {
                _pagedDataSource.CurrentPageIndex = 0;
            }

            ViewState["TotalPages"] = _pagedDataSource.PageCount;

            dlNewsArchive.DataSource = _pagedDataSource;
            dlNewsArchive.DataBind();
        }

        /// <summary>
        /// Gets the QueryString.
        /// </summary>
        /// <returns>Returns a string containing the QueryString.</returns>
        public string GetQueryString()
        {
            NameValueCollection nvc = new NameValueCollection();

            nvc.Add("i", ddlResultsPerPage.SelectedValue.ToString());

            if (Request.QueryString["p"] != null)
            {
                nvc.Add("p", Request.QueryString["p"].ToString());
            }
            else
            {
                nvc.Add("p", "1");
            }

            return GeneralTools.GenerateQueryString(nvc);
        }

        /// <summary>
        /// Creates the pagination.
        /// </summary>
        private void CreatePagination()
        {
            if (Request.QueryString["p"] != null)
            {
                List<WebControl> links = GeneralTools.CreatePagination(5, Convert.ToInt32(ViewState["TotalPages"]), Convert.ToInt32(Request.QueryString["p"]), Request.Url.Query, Request.Path);
                List<WebControl> links2 = GeneralTools.CreatePagination(5, Convert.ToInt32(ViewState["TotalPages"]), Convert.ToInt32(Request.QueryString["p"]), Request.Url.Query, Request.Path);

                for (int i = 0; i < links.Count; i++)
                {
                    if (links[i] is HyperLink)
                    {
                        HyperLink link = (HyperLink)links[i];
                        HyperLink link2 = (HyperLink)links2[i];

                        panTopPagination.Controls.Add(link);
                        panPagination.Controls.Add(link2);
                    }

                    else if (links[i] is Label)
                    {
                        Label label = (Label)links[i];
                        Label label2 = (Label)links2[i];

                        panTopPagination.Controls.Add(label);
                        panPagination.Controls.Add(label2);
                    }
                }
            }
            else
            {
                List<WebControl> links = GeneralTools.CreatePagination(5, Convert.ToInt32(ViewState["TotalPages"]), 1, Request.Url.Query, Request.Path);

                List<WebControl> links2 = GeneralTools.CreatePagination(5, Convert.ToInt32(ViewState["TotalPages"]), 1, Request.Url.Query, Request.Path);

                for (int i = 0; i < links.Count; i++)
                {
                    if (links[i] is HyperLink)
                    {
                        HyperLink link = (HyperLink)links[i];
                        HyperLink link2 = (HyperLink)links2[i];

                        panTopPagination.Controls.Add(link);
                        panPagination.Controls.Add(link2);
                    }

                    else if (links[i] is Label)
                    {
                        Label label = (Label)links[i];
                        Label label2 = (Label)links2[i];

                        panTopPagination.Controls.Add(label);
                        panPagination.Controls.Add(label2);
                    }
                }
            }
        }

        /// <summary>
        /// Localizes the controls of the site, based on the current UI Culture.
        /// </summary>
        private void LocalizeControls()
        {
            hyLinkLatestNews.Text = GetLocalResourceObject("hyLinkLatestNewsText").ToString();
            lblLatestNewsHeader.Text = GetLocalResourceObject("lblLatestNewsHeaderText").ToString();
            lblNewsArchiveHeader.Text = GetLocalResourceObject("lblNewsArchiveHeaderText").ToString();
            lblResultsPerPage.Text = GetLocalResourceObject("lblResultsPerPageText").ToString();
        }

        // Event fires when the datalist is DataBound
        protected void dlNewsArchive_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Separator)
            {
                //Truncates the text to fit in the archive box
                Label lblNewsArchiveText = (Label)e.Item.FindControl("lblNewsArchiveText");
                lblNewsArchiveText.Text = GeneralTools.TruncateString(lblNewsArchiveText.Text, 100, ".");

                //Localizes the "Read more" link based on the Current UI culture
                HyperLink hyLinkNewsArchive = (HyperLink)e.Item.FindControl("hyLinkNewsArchive");
                hyLinkNewsArchive.Text = GetLocalResourceObject("hyLinkLatestNewsText").ToString();
            }
        }

        //Event fired when the selected index of the result per page dropdown list has changed
        protected void ddlResultsPerPage_SelectedIndexChanged(object sender, EventArgs e)
        {
            string url = Request.Path + GetQueryString();

            Response.Redirect(url);
        }
    }
}